import 'package:fate_blind_box/network/http_request.dart';
import 'package:fate_blind_box/utils/default/date_time_utils.dart';
import 'package:fate_blind_box/utils/loading.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import '../../../../theme/theme_color.dart';
import '../../../../widget/date_picker/flutter_datetime_picker.dart';
import 'package:date_format/date_format.dart';
import '../../../Home/activity/act_list_model.dart';
import '../../address/address_chose_page.dart';
import '../../address/adress_chose_poi_model.dart';
import 'package:dio/dio.dart' as dioFile;

class ActPubListController extends GetxController {
  //海报
  String photoCoverId = 'photoCoverId';
  String photoCoverUrl = '';

  //活动主题
  String actTitleVCId = 'actTitleVCId';
  TextEditingController actTitleVC = TextEditingController(); //活动主题
  //开始时间
  String startTimeId = 'startTimeId';
  TextEditingController startTimeVC = TextEditingController();
  DateTime startDate = DateTime.now();

  //结束时间
  TextEditingController endTimeVC = TextEditingController();
  String endTimeId = 'endTimeId'; //活动时间
  DateTime endDate = DateTime.now();

  //选择地址
  String addressViewId = 'addressViewId';
  TextEditingController addressVC = TextEditingController();
  AddressChosePoiDataModel choseAddressDetailsModel =
      AddressChosePoiDataModel(); //选中地址模型数据
  String actiPhone = 'actiPhone'; //报名设置-手机号
  String actiName = ''; //报名设置-名字

  //时间费用
  String expenseViewId = 'expenseViewId';
  TextEditingController expenseVC = TextEditingController();


  List<String> expenseList = ['免费', '现场收费'];
  int expenseType = 0; //0免费 1现场收费

  //发布到首页
  String publishToHomeId = 'publishToHomeId';
  bool isPublishToHome = false;

  //发布到我的群
  String publishToMyGroupId = 'publishToMyGroupId';
  bool isPublishToMyGroup = false;

  //活动描述
  TextEditingController actDetailsVC = TextEditingController();
  String actDetailsDes = '';

  //活动id
  String preViewId = 'actPreViewId';

  //预览
  FuturePopular preViewModel = FuturePopular();

  //选择费用
  showChoseExpense() {
    showModalBottomSheet(
        context: Get.context!,
        builder: (BuildContext context) {
          return SizedBox(
            height: 200,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                const SizedBox(
                  height: 10,
                ),
                const Text(
                  '选择收费方式',
                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                ),
                Expanded(child: Container()),
                GestureDetector(
                    onTap: () {
                      updateActExpense(expenseList.first);
                    },
                    child: Container(
                      alignment: Alignment.center,
                      width: 1.sw,
                      height: 55,
                      color: Colors.white,
                      child: Text(expenseList.first),
                    )),
                Divider(
                  color: ThemeColor.sendMsgColor,
                  height: 1,
                ),
                GestureDetector(
                  onTap: () {
                    updateActExpense(expenseList.last);
                  },
                  child: Container(
                    alignment: Alignment.center,
                    width: 1.sw,
                    height: 60,
                    color: Colors.white,
                    child: Text(expenseList.last),
                  ),
                ),
              ],
            ),
          );
        });
  }

  void updateActExpense(String name) {
    Navigator.pop(Get.context!);
    expenseVC.text = name;
    preViewModel.actiCost = name;
    update([expenseViewId]);
  }

  //选择封面或者详情
  choseCoverAndDetails(String url) {
    photoCoverUrl = url;
    preViewModel.actiCover = url;
    update([photoCoverId]);
  }

  //选择开始时间
  void choseTimeView({bool isEndTime = false}) {
    DatePicker.showDateTimePicker(
      Get.context!,
      showTitleActions: true,
      minTime: DateTime.now(),
      maxTime: DateTime(2030, 12, 31),
      onChanged: (date) {},
      onConfirm: (date) {
        if (isEndTime) {
          endTimeVC.text = formatDate(
              date, [yyyy, '-', mm, '-', dd, ' ', hh, ':', nn, ':', ss]);
          endDate = date;

          update([endTimeId]);
        } else {
          startDate = date;
          startTimeVC.text = formatDate(
              date, [yyyy, '-', mm, '-', dd, ' ', hh, ':', nn, ':', ss]);
          preViewModel.actiTime = startTimeVC.text;
          update([startTimeId]);
        }
      },
      currentTime: DateTime.now(),
    );
  }

  //选择开始地点
  void chosePlaceView() {
    Get.to(AddressChosePage(
      finishBlock: (AddressChosePoiDataModel choseModel) {
        choseAddressDetailsModel = choseModel;
        String addressStr =
            "${choseModel.address ?? ''}${choseModel.name ?? ''}";
        addressVC.text = addressStr;
        preViewModel.actiProvince = choseModel.pname;
        preViewModel.actiCity = choseModel.cityname;
        preViewModel.actiArea = choseModel.adname;
        preViewModel.actiAddr = addressStr;
        update([addressViewId]);
      },
    ));
  }

  //发布
  void clickPublishAction() async {
    String actiTitle = actTitleVC.text;
    String startTime = startTimeVC.text;
    String endTime = endTimeVC.text;
    //保存到草稿箱不需要校验
    if (photoCoverUrl.isEmpty) {
      toast('请上传海报图片');
      return;
    }
    if (actiTitle.isEmpty) {
      toast('请输入标题');
      return;
    }
    if (startTime.isEmpty) {
      toast('请选择开始时间');
      return;
    }
    if (endTime.isEmpty) {
      toast('请选择结束时间');
      return;
    }
    if (choseAddressDetailsModel.longitude == 0) {
      toast('请选择地点');
      return;
    }

    if (actDetailsDes.isEmpty) {
      toast('请选择活动描述');
      return;
    }

    Map<String, dynamic> dataMap = {
      'brief': dioFile.MultipartFile.fromFileSync(photoCoverUrl),
      'actiTitle': actiTitle,
      'startTime': DateTimeUtils.dateToTimestamp(startDate),
      'endTime': DateTimeUtils.dateToTimestamp(endDate),
      'actiCost': expenseType,
      'actiProvice': choseAddressDetailsModel.pname,
      'city': choseAddressDetailsModel.cityname,
      'area': choseAddressDetailsModel.adname,
      'actiAddr': choseAddressDetailsModel.address,
      'actiLog': choseAddressDetailsModel.longitude,
      'actiLat': choseAddressDetailsModel.latitude,
      'actiDescribe': actDetailsDes,
      'isDisplay': isPublishToHome ? 1 : 0,
      'isPublish': isPublishToMyGroup ? 1 : 0,
    };
    String apiUrl = 'member/activity/release';
    var res = await HttpRequest.uploadFile(apiUrl, params: dataMap);
    if (res['code'] == 0) {
      final data = res['data'];
      if (data != null) {
        toast('保存成功');
        Get.back();
      } else {
        toast(res['msg']);
      }
    }
  }

  //预览
  void clickPrelishAction() async {
    String actiTitle = actTitleVC.text;
    String startTime = startTimeVC.text;
    String endTime = endTimeVC.text;
    Map<String, dynamic> dataParams = {};
    if (photoCoverUrl.isNotEmpty) {
      dataParams['brief'] = dioFile.MultipartFile.fromFileSync(photoCoverUrl);
    }
    if (actiTitle.isNotEmpty) {
      dataParams['actiTitle'] = actiTitle;
    }

    if (startTime.isNotEmpty) {
      dataParams['startTime'] = DateTimeUtils.dateToTimestamp(startDate);
    }

    if (endTime.isNotEmpty) {
      dataParams['endTime'] = DateTimeUtils.dateToTimestamp(endDate);
    }

    if (expenseType > 0) {
      dataParams['actiCost'] = expenseType;
    }

    if (choseAddressDetailsModel.pname.isNotEmpty) {
      dataParams['actiProvice'] = choseAddressDetailsModel.pname;
    }

    if (choseAddressDetailsModel.cityname.isNotEmpty) {
      dataParams['city'] = choseAddressDetailsModel.cityname;
    }

    if (choseAddressDetailsModel.adname.isNotEmpty) {
      dataParams['area'] = choseAddressDetailsModel.adname;
    }

    String address = choseAddressDetailsModel.address ?? '';
    if (address.isNotEmpty) {
      dataParams['actiAddr'] = choseAddressDetailsModel.address ?? '';
    }

    if (choseAddressDetailsModel.longitude > 0) {
      dataParams['actiLog'] = choseAddressDetailsModel.longitude;
    }

    if (choseAddressDetailsModel.latitude > 0) {
      dataParams['actiLat'] = choseAddressDetailsModel.latitude;
    }

    if (actDetailsDes.isNotEmpty) {
      dataParams['actiDescribe'] = actDetailsDes;
    }

    if (isPublishToHome) {
      dataParams['isDisplay'] = isPublishToHome ? 1 : 0;
    }

    if (isPublishToMyGroup) {
      dataParams['isPublish'] = isPublishToMyGroup ? 1 : 0;
    }

    String apiUrl = 'member/activity/preview';
    if (dataParams.keys.isEmpty) {
      Get.back();
    } else {
      var res = await HttpRequest.uploadFile(apiUrl, params: dataParams);
      if (res['code'] == 0) {
        final data = res['data'];
        if (data != null) {
          toast('保存成功');
          String actId = data['id'];
          var cacheId = await Provider.getCache(preViewId);
          if (cacheId == null || cacheId == '') {
            await Provider.cache(preViewId, actId);
          }
          Get.back();
        } else {
          toast(res['msg']);
          Get.back();
        }
      } else {
        Get.back();
      }
    }
  }

  //获取预览详情页面数据
  void getActPreviewDetails() async {
    String cacheId = await Provider.getCache('actPreViewId');
    if (cacheId.isNotEmpty) {
      var res = await HttpRequest.request('member/activity/tempDetails',
          params: {'activityId': cacheId});
      preViewModel = FuturePopular.fromJson(res['data']);
      actTitleVC.text = preViewModel.actiTitle ?? '';
      startTimeVC.text = preViewModel.startTime ?? '';
      endTimeVC.text = preViewModel.endTime ?? '';
      addressVC.text = preViewModel.actiAddr ?? '';
      actDetailsVC.text = preViewModel.actiDescribe;
      expenseVC.text=preViewModel.actiCost??'免费';
      update([
        photoCoverId,
        actTitleVCId,
        startTimeId,
        endTimeId,
        addressViewId,
        expenseViewId,
        publishToHomeId,
        publishToMyGroupId
      ]);
    }
  }
}
